// pages/profile/profile.ts
import { MerchantAPI } from '../../utils/api'

interface PersonalInfo {
  userId?: number | string;
  userName?: string;
  nickName?: string;
  phonenumber?: string;
  email?: string;
  sex?: string;
  sexName?: string;
  avatar?: string;
  displayName?: string;
}

interface ProfilePageData {
  userInfo: PersonalInfo;
  statusBarHeight: number;
  loading: boolean;
}

Page({
  data: {
    userInfo: {} as PersonalInfo,
    statusBarHeight: 0,
    loading: false
  } as ProfilePageData,

  onLoad() {
    const systemInfo = wx.getSystemInfoSync();
    const statusBarHeight = systemInfo.statusBarHeight || 0;
    
    this.setData({
      statusBarHeight
    });
    
    this.loadUserInfo();
  },

  onShow() {
    this.loadUserInfo();
  },

  // 加载用户信息
  async loadUserInfo() {
    // 先加载缓存数据，保证页面快速渲染
    const cachedInfo = wx.getStorageSync('merchantPersonalInfo');
    if (cachedInfo) {
      this.setData({
        userInfo: this.formatPersonalInfo(cachedInfo)
      });
    }

    this.setData({ loading: true });

    try {
      const response = await MerchantAPI.getPersonalInfo();
      if (response.code === 200 && response.data) {
        const formatted = this.formatPersonalInfo(response.data);
        this.setData({
          userInfo: formatted
        });
        wx.setStorageSync('merchantPersonalInfo', response.data);
      }
    } catch (error) {
      console.error('获取个人信息失败:', error);
    } finally {
      this.setData({ loading: false });
    }
  },

  // 格式化个人信息
  formatPersonalInfo(data: any): PersonalInfo {
    if (!data) {
      return {};
    }

    const displayName = data.nickName || data.userName || data.phonenumber || '商家用户';
    const sexNameMap: Record<string, string> = {
      '0': '男',
      '1': '女',
      '2': '未知'
    };

    return {
      userId: data.userId,
      userName: data.userName,
      nickName: data.nickName,
      phonenumber: data.phonenumber,
      email: data.email,
      sex: data.sex,
      sexName: data.sexName || sexNameMap[data.sex] || '未知',
      avatar: data.avatar,
      displayName
    };
  },

  /**
   * 页面导航
   */
  navigateTo(e: any) {
    const url = e.currentTarget.dataset.url;
    
    if (url) {
      wx.navigateTo({
        url
      });
    }
  },

  /**
   * 联系客服
   */
  contactService() {
    wx.showModal({
      title: '联系客服',
      content: '客服电话：400-123-4567\n服务时间：工作日 9:00-18:00',
      showCancel: true,
      cancelText: '取消',
      confirmText: '拨打电话',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '400-123-4567',
            fail: () => {
              wx.showToast({
                title: '拨打失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  /**
   * 常见问题
   */
  openFAQ() {
    wx.showModal({
      title: '常见问题',
      content: '1. 如何提现？\n2. 如何修改银行卡？\n3. 如何查看交易记录？\n\n更多问题请联系客服',
      showCancel: false,
      confirmText: '知道了'
    });
  },

  /**
   * 协议与说明
   */
  openAgreement() {
    wx.showModal({
      title: '协议与说明',
      content: '《商家服务协议》\n《平台使用规范》\n《费用说明及结算规则》\n\n请仔细阅读并遵守相关协议',
      showCancel: false,
      confirmText: '我知道了'
    });
  },

  /**
   * 隐私政策
   */
  openPrivacy() {
    wx.showModal({
      title: '隐私政策',
      content: '我们重视您的隐私保护：\n\n1. 信息收集：仅收集必要的商家信息\n2. 信息使用：用于订单处理和服务提供\n3. 信息保护：采用加密技术保护数据安全\n\n详细内容请查看完整隐私政策',
      showCancel: false,
      confirmText: '知道了'
    });
  },

  /**
   * 清理缓存
   */
  clearCache() {
    wx.showModal({
      title: '清理缓存',
      content: '清理缓存会删除本地临时数据，但不会影响您的账户信息。是否继续？',
      confirmText: '确认清理',
      confirmColor: '#5cb85c',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '清理中...',
            mask: true
          });

          // 模拟清理缓存过程
          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '缓存已清理',
              icon: 'success',
              duration: 2000
            });
          }, 1000);
        }
      }
    });
  },

  /**
   * 确认退出登录
   */
  confirmLogout() {
    wx.showModal({
      title: '退出登录',
      content: '确定要退出登录吗？退出后将无法接收新订单通知。',
      confirmText: '确认退出',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          this.handleLogout();
        }
      }
    });
  },

  /**
   * 处理退出登录
   */
  async handleLogout() {
    try {
      wx.showLoading({
        title: '退出中...',
        mask: true
      });

      // 调用后端退出登录接口
      const { MerchantAPI } = require('../../utils/api');
      await MerchantAPI.logout();
      
      // 清除本地存储
      wx.removeStorageSync('merchantToken');
      wx.removeStorageSync('merchantUserInfo');
      wx.removeStorageSync('merchantPersonalInfo');
      
      wx.hideLoading();
      wx.showToast({
        title: '已退出登录',
        icon: 'success'
      });
      
      // 跳转到登录页
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/auth/auth'
        });
      }, 1500);
      
    } catch (error) {
      console.error('退出登录失败:', error);
      wx.hideLoading();
      
      // 即使后端接口调用失败，也清除本地数据
      wx.removeStorageSync('merchantToken');
      wx.removeStorageSync('merchantUserInfo');
      wx.removeStorageSync('merchantPersonalInfo');
      
      wx.showToast({
        title: '已退出登录',
        icon: 'success'
      });
      
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/auth/auth'
        });
      }, 1500);
    }
  }
});